<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Wallet;
use App\Library\ETH\EthereumFunction;
use App\Library\BTC\BitcoinFunction;
use App\Library\OBA\ObaFunction;

/**
 * 更新系统钱包余额.
 */
class WalletBalance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wallet:balance';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //获取所有未锁定的系统钱包
        $wallets = Wallet::where('status', 0)->get();

        foreach ($wallets as $wallet) {
            if (collect($wallet->currency)->count() > 0) {
                /*if ($wallet->currency->name_en == 'ETH') {
                    $eth = new EthereumFunction();
                    $balance = $eth->getBalanceByAddress($wallet->address);
                    //eth节点报错，保证程序能正常运行
                    if ($balance == '') {
                        continue;
                    }
                    $wallet->update([
                        'balance' => $balance,
                        'block_balance' => $balance,
                    ]);
                }*/

                if ($wallet->currency->name_en == 'OBA') {
                    $oba = new ObaFunction();
                    $res = $oba->getBalanceByAddress($wallet->address);
                    if (!is_array($res)) {
                        $wallet->update([
                                'balance' => $res,
                                'block_balance' => $res,
                            ]);                        
                    }

                }
                if (in_array($wallet->currency->name_en, ['BTC', 'LTC', 'DGC'])) {
                    $btc = new BitcoinFunction($wallet->currency->name_en);
                    $balance = $btc->getBalanceByAddress($wallet->address);
                    $wallet->update([
                        'balance' => $balance,
                        'block_balance' => $balance,
                    ]);
                }                
            }

        }
    }
}
